package cn.powertime.evaluation.facade.impl;

import cn.powertime.evaluation.Constants;
import cn.powertime.evaluation.annotation.Facade;
import cn.powertime.evaluation.entity.CpsUserCollect;
import cn.powertime.evaluation.exception.BusinessException;
import cn.powertime.evaluation.facade.CpsUserCollectFacade;
import cn.powertime.evaluation.service.CpsUserCollectService;
import cn.powertime.evaluation.shiro.ShiroUtils;
import cn.powertime.evaluation.vo.ShiroUserInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Facade
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public class CpsUserCollectFacadeImpl implements CpsUserCollectFacade {

    @Autowired
    private CpsUserCollectService userCollectService;

    public boolean checkTopicOnly(Long userId, Long topicId) {
        QueryWrapper<CpsUserCollect> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("topic_id", topicId);
        wrapper.eq("status", Constants.STATUS_NORMAL);
        return userCollectService.count(wrapper) > 0;
    }

    @Override
    public boolean collect(Integer type, Long topicId) {
        ShiroUserInfo userInfo = ShiroUtils.getUserInfo();
        boolean flag = false;
        if (type == 1) {
            boolean b = checkTopicOnly(userInfo.getId(), topicId);
            if (b) {
                log.error("ID为" + topicId + "的习题已经收藏");
                throw new BusinessException("ID为" + topicId + "的习题已经收藏");
            }
            CpsUserCollect userCollect = new CpsUserCollect();
            userCollect.setId(IdWorker.getId());
            userCollect.setUserId(userInfo.getId());
            userCollect.setTopicId(topicId);
            flag = this.userCollectService.add(userCollect);
        } else if (type == 0) {
            boolean b = checkTopicOnly(userInfo.getId(), topicId);
            if (b == false) {
                log.error("ID为" + topicId + "的习题已经取消收藏");
                throw new BusinessException("ID为" + topicId + "的习题已经取消收藏");
            }
            flag = this.userCollectService.delete(userInfo.getId(), topicId);
        }
        return flag;
    }

}
